<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Validate;
use app\facade\Redis;
use app\models\{User as Users, Money, Moneylog, Activacode, Commvote, CommvoteLog, LockmoneyLog};
use think\Facade\Config as Configs;


class User extends Base
{
    public function User()
    {
        $ModelFun = new Users();
        $data = $this->request->get();
        $list = $ModelFun->alias('u')->order('u.id desc')->leftjoin('activacode a', 'u.id = a.user_id');
        if (!empty($data['mobile'])) {
            $list = $list->where('u.id|u.mobile', $data['mobile']);
        }
        if (!empty($data['code'])) {
            $list = $list->where('u.code', $data['code']);
        }
        if (!empty($data['ispartner'])) {
            $list = $list->where('u.ispartner', $data['ispartner']);
        }
        if (!empty($data['isagent'])) {
            $list = $list->where('u.isagent', $data['isagent']);
        }
        if (!empty($data['status'])) {
            $list = $list->where('u.status', $data['status']);
        }
        if (!empty($data['iskeys'])) {
            if ($data['iskeys'] == 1) {
                $list = $list->whereNotNull('a.activakeys');
            } else {
                $list = $list->whereNull('a.activakeys');
            }
        }
        if (!empty($data['pmobile'])) {
            $pid = (new Users())->where('id|mobile', $data['pmobile'])->value('id');
            $list = $list->where('u.pid', $pid);
        }
        $data['oldlockmoney'] =  (new Users())->sum('oldlockmoney');
        $data['oldlockdays'] =  (new Users())->sum('oldlockdays');
        $list = $list->field('u.*,a.activakeys')->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            if ($user['pid'] > 0) {
                $user['pmobile'] = (new Users())->where('id', $user['pid'])->value('mobile');
            } else {
                $user['pmobile'] = '';
            }
            return $user;
        });
        return view('', ['list' => $list, 'data' => $data]);
    }

    //修改
    public function User_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'mobile' => 'require',
            ], [
                'id.require' => '用户ID不能为空',
                'mobile.require' => '手机号码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = (new Users())->where('id', $data['id'])->find();
            $saveDate = [];
            if (!empty($data['mobile']) && $data['mobile'] != $user['mobile']) {
                $ismobile = (new Users())->where('mobile', $data['mobile'])->find();
                if (!empty($ismobile)) {
                    return json(['status' => 1, 'data' => [], 'msg' => '手机用户已存在']);
                }
                $saveDate['mobile'] = $data['mobile'];
            } else {
                unset($data['mobile']);
            }
            if (!empty($data['password'])) {
                $saveDate['password'] = md5(md5($data['password']));
            }
            if (!empty($data['trade'])) {
                $saveDate['trade'] = md5(md5($data['trade']));
            }
            if (empty($saveDate)) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            $result = (new Users())->where('id', $data['id'])->update($saveDate);
            if ($result) {
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $row = (new Users())->where('id', $id)->find();
            return view('', ['row' => $row]);
        }
    }

    public function User_add()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'mobile' => 'require',
                'invit' => 'require|gt:0',
                'password' => 'require',
                'trade' => 'require',
            ], [
                'mobile.require' => '手机号码不能为空',
                'invit.require' => '邀请码不能为空',
                'invit.gt' => '邀请码错误',
                'password.require' => '登录密码不能为空',
                'trade.require' => '支付密码不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断邀请码是否存在
            $code = (new Users())->where('code', $data['invit'])->find();
            if (empty($code)) {
                return json(['status' => 1, 'data' => [], 'msg' => '邀请码错误']);
            }
            //判断手机号码是否已存在
            $user = (new Users())->where('mobile', $data['mobile'])->find();
            if (!empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '手机号码已注册']);
            }
            $structure = $code['structure'] . ',' . $code['id'];
            $people = explode(',', $structure);
            $people = array_filter($people); //给上级人员增加团队人数
            $mycode = recode(new Users());
            $keys = PrivateKey((new Users()));
            $coin = Configs::get('config.coins');
            Db::startTrans();
            try {
                if (count($people) > 0) {
                    (new Users())->where('id', 'in', $people)->setInc('teampople');
                }
                $id = (new Users())->insertGetId([
                    'mobile' => $data['mobile'],
                    'privatekey' => $keys,
                    'password' => md5(md5($data['password'])),
                    'trade' => md5(md5($data['trade'])),
                    'code' => $mycode,
                    'pid' => $code['id'],
                    'structure' => $structure,
                    'created' => date('Y-m-d H:i:s')
                ]);
                if (count($coin) > 0) {
                    $moneydata = [];
                    foreach ($coin as $k => $v) {
                        $moneydata[$k]['user_id'] = $id;
                        $moneydata[$k]['type'] = $k;
                        $moneydata[$k]['created'] = date('Y-m-d H:i:s');
                    }
                    $moneydata = array_merge($moneydata);
                    if (!empty($moneydata)) {
                        (new Money())->insertAll($moneydata);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '注册失败，请重试']);
                // $this->result($e->getMessage(), 1, '注册失败，请重试');
            }
            return json(['status' => 0, 'data' => [], 'msg' => '注册成功']);
        } else {
            return view();
        }
    }

    public function userstart()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'type' => 'require|in:1,2,3,4,6',
        ], [
            'id.require' => '用户ID不能为空',
            'type.require' => '修改类型不能为空',
            'type.in' => '修改类型不正确'
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        $user = (new Users())->where('id', $data['id'])->find();
        if (empty($user)) {
            return json(['status' => 1, 'data' => [], 'msg' => '用户不存在']);
        }
        if ($data['type'] == 1) {
            $status = $user['ispartner'] == 1 ? 2 : 1;
            $res = (new Users())->where('id', $data['id'])->update(['ispartner' => $status]);
        } elseif ($data['type'] == 2) {
            $status = $user['isagent'] == 1 ? 2 : 1;
            $res = (new Users())->where('id', $data['id'])->update(['isagent' => $status]);
        } elseif ($data['type'] == 3) {
            $status = $user['status'] == 1 ? 2 : 1;
            $res = (new Users())->where('id', $data['id'])->update(['status' => $status]);
        } elseif ($data['type'] == 4) {
            $status = $user['switchclose'] == 1 ? 2 : 1;
            $res = (new Users())->where('id', $data['id'])->update(['switchclose' => $status]);
        } elseif ($data['type'] == 6) {
            $status = $user['teamstatus'] == 1 ? 2 : 1;
            $res = (new Users())->where('id', $data['id'])->update(['teamstatus' => $status]);
        } else {
            return json(['status' => 1, 'data' => [], 'msg' => '参数错误']);
        }
        if ($res) {
            return json(['status' => 0, 'msg' => '操作成功']);
        } else {
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }

    public function Money()
    {
        $ModelFun = new Money();
        $data = $this->request->get();
        $list = $ModelFun->order('user_id desc');
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (isset($data['daotype']) && $data['daotype'] == 2) {
            $name = '用户资产信息导出表';
            $header =   ["用户id", "手机号", "资产类型",  "可用资产", "冻结资产", "推荐人用户ID", "推荐人手机号"];
            $userlist = (new Money())->alias('m')->field('m.*,u.mobile,u.pid,u.oldlockmoney')->join('User u', 'u.id = m.user_id');
            if (!empty($data['type'])) {
                $userlist = $userlist->where('m.type', $data['type']);
            }
            if (!empty($data['mobile'])) {
                $list = $list->where('u.mobile', $data['mobile']);
            }
            $userlist = $userlist->select();
            foreach ($userlist as $key => $v) {
                $v['pmobile'] = (new Users())->where('id', $v['pid'])->value('mobile');
                $datb[] = [
                    $v['user_id'],
                    $v['mobile'],
                    Configs::get('config.coins.' . $v['type']),
                    $v['money'],
                    $v['freezemoney'],
                    $v['pid'],
                    $v['pmobile'],
                ];
            }
            excelExport($name, $header, $datb);
        }
        $totals = [];
        $coin = Configs::get('config.coins');
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            $user['typetext'] = Configs::get('config.coins.' . $user['type']);
            return $user;
        });
        return view('', ['list' => $list, 'coin' => $coin, 'totals' => $totals]);
    }

    public function Money_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'user_id' => 'require|gt:0',
                'type' => 'require|gt:0',
                'money' => 'require|float',
            ], [
                'user_id.require' => '用户ID不能为空',
                'user_id.gt' => '用户必须大于0',
                'type.require' => '币种类型不能为空',
                'type.gt' => '币种类型必须大于0',
                'money.require' => '修改数目不能为空',
                'money.float' => '修改数目必须是数字或小数',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $money = (new Money())->where(['user_id' => $data['user_id'], 'type' => $data['type']])->find();
            if (empty($money)) {
                return json(['status' => 1, 'data' => [], 'msg' => '币种钱包不存在']);
            }
            if ($data['money'] == 0 || ($data['money'] < 0 && abs($data['money']) > $money['money'])) {
                return json(['status' => 1, 'data' => [], 'msg' => '修改数目不能为0或修改后钱包数目为负数']);
            }
            Db::startTrans();
            try {
                (new Money())->where(['user_id' => $data['user_id'], 'type' => $data['type'], 'money' => $money['money']])->setInc('money', $data['money']);
                (new Moneylog())->insert([
                    'user_id' => $data['user_id'],
                    'befores' => $money['money'],
                    'money' => $data['money'],
                    'after' => ($money['money'] + $data['money']),
                    'cointype' => $data['type'],
                    'type' => 1,
                    'info' => '系统充值，系统ID:' . session('admin_id')
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '修改失败，请重试']);
                // $this->result($e->getMessage(), 1, '注册失败，请重试');
            }
            return json(['status' => 0, 'data' => [], 'msg' => '修改成功']);
        } else {
            return view();
        }
    }

    public function lockmoney_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'user_id' => 'require|gt:0',
                'money' => 'require|float',
            ], [
                'user_id.require' => '用户ID不能为空',
                'user_id.gt' => '用户必须大于0',
                'money.require' => '修改数目不能为空',
                'money.float' => '修改数目必须是数字或小数',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $user = (new Users())->where(['id' => $data['user_id']])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '用户不存在']);
            }
            if ($data['money'] == 0 || ($data['money'] < 0 && abs($data['money']) > $user['lockmoney'])) {
                return json(['status' => 1, 'data' => [], 'msg' => '修改数目不能为0或修改后锁仓数目为负数']);
            }
            Db::startTrans();
            try {
                (new Users())->where(['id' => $data['user_id'], 'lockmoney' => $user['lockmoney']])->setInc('lockmoney', $data['money']);
                (new LockmoneyLog())->insert([
                    'user_id' => $data['user_id'],
                    'money' => $data['money'],
                    'info' => '系统修改，系统ID:' . session('admin_id')
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '修改失败，请重试']);
                // $this->result($e->getMessage(), 1, '注册失败，请重试');
            }
            return json(['status' => 0, 'data' => [], 'msg' => '修改成功']);
        } else {
            return view();
        }
    }

    public function userskeys()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
        ], [
            'id.require' => '用户ID不能为空',
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        $user = (new Users())->where('id', $data['id'])->find();
        if (empty($user)) {
            return json(['status' => 1, 'data' => [], 'msg' => '用户不存在']);
        }
        //查询是否购买私钥
        $userkeys = (new Activacode())->where('user_id', $data['id'])->find();
        if (empty($userkeys)) {
            $activakeys = ActivaCodeK(new Activacode());
            $res = (new Activacode())->insert([
                'user_id' => $data['id'],
                'type' => 2,
                'activakeys' => $activakeys,
            ]);
        } else {
            $res =  (new Activacode())->where('user_id', $data['id'])->delete();
        }
        if ($res) {
            return json(['status' => 0, 'msg' => '操作成功']);
        } else {
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }

    public function Money_log()
    {
        $ModelFun = new Moneylog();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        if (!empty($data['pmobile'])) {
            $comeid = (new Users())->where('id|mobile', $data['pmobile'])->value('id');
            $list = $list->where('comeuser_id', $comeid);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (!empty($data['cointype'])) {
            $list = $list->where('cointype', $data['cointype']);
        }
        $coin = Configs::get('config.coins');
        $types = Configs::get('config.moneytype');
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            $user['typetext'] = Configs::get('config.coins.' . $user['cointype']);
            $user['moneytext'] = Configs::get('config.moneytype.' . $user['type']);
            if ($user['comeuser_id'] > 0) {
                $user['comemobile'] = (new Users())->where('id', $user['comeuser_id'])->value('mobile');
            } else {
                $user['comemobile'] = '';
            }
            return $user;
        });
        return view('', ['list' => $list, 'coin' => $coin, 'types' => $types]);
    }

    public function Commvote()
    {
        $ModelFun = new Commvote();
        $data = $this->request->get();
        $list = $ModelFun->order('dates desc');
        if (!empty($data['dates'])) {
            $list = $list->where('dates', $data['dates']);
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function commvote_add()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        $validate = new Validate([
            'dates' => 'require',
        ], [
            'dates.require' => '投票日期不能为空',
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        if ($data['dates'] < date('Y-m-d')) {
            return json(['status' => 1, 'data' => [], 'msg' => '当日之前的投票不可添加']);
        }
        $Commvote = (new Commvote())->where(['dates' => $data['dates'], 'status' => 1])->find();
        if (!empty($Commvote)) {
            return json(['status' => 1, 'data' => [], 'msg' => '已存在当日进行中的投票']);
        }
        Db::startTrans();
        try {
            (new Commvote())->insert([
                'dates' => $data['dates']
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => '修改失败，请重试']);
            // $this->result($e->getMessage(), 1, '注册失败，请重试');
        }
        return json(['status' => 0, 'data' => [], 'msg' => '修改成功']);
    }

    public function commvotelog()
    {
        $ModelFun = new Commvotelog();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['code'])) {
            $list = $list->where('code', $data['code']);
        }
        if (!empty($data['mobile'])) {
            $user_id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $user_id);
        }
        if (!empty($data['code'])) {
            $list = $list->where('code', $data['code']);
            $code = $data['code'];
        } else {
            $code = 0;
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['mobile'] = '';
            if ($result['user_id'] > 0) {
                $result['mobile'] = (new Users())->where('id', $result['user_id'])->value('mobile');
            }
            return $result;
        });
        return view('', ['list' => $list, 'code' => $code]);
    }

    public function commvotestr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'code' => 'require',
                'mobile' => 'require',
                'status' => 'require',
                'price' => 'require',
                'created' => 'require',
            ], [
                'id.require' => '投票ID不能为空',
                'mobile.require' => '手机号码不能为空',
                'status.require' => '是否投票不能为空',
                'price.require' => '投票价格不能为空',
                'created.require' => '投票时间不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = (new CommvoteLog())->where(['code' => $data['code'], 'mobile' => $data['mobile']])->find();
            if (!empty($user)) {
                return json(['status' => 1, 'msg' => '该编号已投票，请勿重复投票']);
            }
            $result = (new CommvoteLog())->allowfield(true)->save($data);
            if ($result) {
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $code = $this->request->get('code');
            $row = (new Commvote())->where('id', $code)->find();
            return view('', ['row' => $row]);
        }
    }

    public function commvotesta()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'type' => 'require|in:1,2,3',
        ], [
            'id.require' => '用户ID不能为空',
            'type.require' => '修改类型不能为空',
            'type.in' => '修改类型不正确'
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        if ($data['type'] == 3) {
            $res = (new Commvote())->where('id', $data['id'])->update(['status' => $data['type']]);
        } else {
            return json(['status' => 1, 'data' => [], 'msg' => '参数错误']);
        }
        if ($res) {
            return json(['status' => 0, 'msg' => '操作成功']);
        } else {
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }
}
